<?php
include 'user_form_lib.php';

if ($s_Action == 'insert-profile') {

    // <editor-fold defaultstate="collapsed" desc="Insert-Profile">
    get_passport_module_action($db_conn, $s_PPO_ModuleID, $s_PPO_ActionID, $a_filterings);
    $v_tmp_firstname = explode(" ", $f_username);
    $v_tmp_firstname = is_array($v_tmp_firstname) ? $v_tmp_firstname[count($v_tmp_firstname) -1] : $f_username ;
    
    $sNew_ID = generate_user_id($f_usertype, $db_conn);

    $a_row = array(
        'userid'            => $sNew_ID,
        'saint'             => $f_saint,
        'username'          => $f_username,
        'firstname'         => $v_tmp_firstname,
        'passwd'            => md5($f_passwd),
        'usertype'          => $f_usertype,
        'usercrew'          => $f_usercrew,
        'gender'            => $f_gender,
        'birthday'          => $f_birthday,
        'baptism_date'      => $f_baptism_date,
        'eucharist_date'    => $f_eucharist_date,
        'confirmation_date' => $f_confirmation_date,
        'email'             => $f_email,
        'mobile'            => $f_mobile,
        'phone'             => $f_phone,
        'address'           => $f_address,
        'note'              => $f_note,
        'creatorid'         => $s_UserID,
        'updaterid'         => $s_UserID,
        'insertdate'        => $f_insertdate,
        'updatedate'        => $f_insertdate,
    );

    db_insert_row($db_conn, $a_row, 'user');

    raise_alert("Đã Tạo!");
    
    local_redirect("user_detail.php?userid=$sNew_ID");
    // </editor-fold>
}
else if ($s_Action == 'checking-file') {

    // <editor-fold defaultstate="collapsed" desc="Checking Data">
    $v_response_json       = new stdClass();
    $v_response_json->code = 0;
    $v_response_json->data = array ( );
    
    $f_files = isset($_FILES['file']) ? $_FILES['file'] : '';
    
    if (!is_array($f_files)) { echo json_encode($v_response_json, true); exit; }

    require_once 'excel_reader.php';
        
    $a_user_info = array (
        0 => array (
            1 => 'saint',
            'username',
            'birthday',
            'gender',
            'team',
            'level',
            'crew',
            'father_saint',
            'father_name',
            'mother_saint',
            'mother_name',
            'address',
            'phone',
            'mobile',
            'parish',
            'baptism_date',
            'eucharist_date',
            'confirmation_date',
        )
    );

    $excel  = new Spreadsheet_Excel_Reader();

    $excel->read($f_files['tmp_name']);

    for ($i = 2; $i <= $excel->sheets[0]['numRows']; $i++) {
        
        $f_flag_next = true;
        $a_tmp       = array ();
        
        foreach ($a_user_info[0] as $key => $value) {
            
            $a_tmp[$key] = isset($excel->sheets[0]['cells'][$i][$key]) ? trim($excel->sheets[0]['cells'][$i][$key]) : '';
            
            //Fix Format-date for dd.mm.yy
            if (in_array($value, array ( 'birthday', 'baptism_date', 'eucharist_date', 'confirmation_date' )) && preg_match('/(?<date>[0-9]{2}).(?<month>[0-9]{2}).(?<year>[0-9]{2})/', $a_tmp[$key], $aTmpMatch)) {
                if ($aTmpMatch['year'] < 50) {
                    $aTmpMatch['year'] = '20' . $aTmpMatch['year'];
                } else {
                    $aTmpMatch['year'] = '19' . $aTmpMatch['year'];
                }
                $a_tmp[$key] = $aTmpMatch['date'] . '-' . $aTmpMatch['month'] . '-' . $aTmpMatch['year'];
            }
            
            if ($a_tmp[$key]) { $f_flag_next = false; }
        }
        
        if ($f_flag_next) { continue; }

        $a_user_info[$i] = array_combine($a_user_info[0], $a_tmp);
    }
    
    ob_clean();
    unset($a_user_info[0]);

    if (empty($a_user_info)) { echo json_encode($v_response_json, true); exit; }
    
    $v_response_json->code = 200;
    $v_response_json->data = array (
        'users'    => $a_user_info,
        'usertype' => $f_usertype,
        'course'   => $f_course,
    );
    echo json_encode($v_response_json, true);
    exit;
    // </editor-fold>
}
else if ($s_Action == 'insert-by-file') {

    // <editor-fold defaultstate="collapsed" desc="Insert-By-File">
    get_passport_module_action($db_conn, $s_PPO_ModuleID, $s_PPO_ActionID, $a_filterings);
    $v_response_json       = new stdClass();
    $v_response_json->code = 0;
    $v_response_json->data = array ( );
    
    $a_user_info = isset($_REQUEST['user_info']) ? $_REQUEST['user_info'] : array();

    if (empty($a_user_info)) { echo json_encode($v_response_json, true); exit; }
    
    $a_users = array();
    
    foreach ($a_user_info as $a_value_info) {

        foreach ($a_value_info as $key => $value) { $a_value_info[$key] = trim($a_value_info[$key]); }
        
        if (!$a_value_info['username']) { continue; }
        
        $string = 'April 15, 2003';

        $a_value_info['birthday']          = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['birthday']);
        $a_value_info['baptism_date']      = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['baptism_date']);
        $a_value_info['eucharist_date']    = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['eucharist_date']);
        $a_value_info['confirmation_date'] = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['confirmation_date']);

        $v_tmp_firstname = explode(" ", $a_value_info['username']);
        $v_tmp_firstname = is_array($v_tmp_firstname) ? $v_tmp_firstname[count($v_tmp_firstname) -1] : $a_value_info['username'] ;

        $v_tmp_passwd = $a_value_info['birthday'] ? date('ymd', strtotime($a_value_info['birthday'])) : date('ymd');
        
        $sNew_ID = generate_user_id($f_usertype, $db_conn);
        
        $a_row = array (
            'userid'            => $sNew_ID,
            'passwd'            => md5($v_tmp_passwd),
            'saint'             => $a_value_info['saint'],
            'username'          => $a_value_info['username'],
            'usertype'          => $f_usertype,
            'firstname'         => $v_tmp_firstname,
            'gender'            => $a_value_info['gender'],
            'birthday'          => $a_value_info['birthday'],
            'baptism_date'      => $a_value_info['baptism_date'],
            'eucharist_date'    => $a_value_info['eucharist_date'],
            'confirmation_date' => $a_value_info['confirmation_date'],
            'address'           => $a_value_info['address'],
            'phone'             => $a_value_info['phone'],
            'mobile'            => $a_value_info['mobile'],
            'parish'           => $a_value_info['parish'],
            'creatorid'         => $s_UserID,
            'updaterid'         => $s_UserID,
            'insertdate'        => $f_insertdate,
            'updatedate'        => $f_insertdate,
        );
        
        db_insert_row($db_conn, $a_row, 'user');
        
        $a_value_info['userid'] = $sNew_ID;
        $a_value_info['passwd'] = $v_tmp_passwd;
        
        if ($a_value_info['team']) {
        
            $a_row = array (
                'userid'     => $sNew_ID,
                'course'     => $a_KhoaHoc_Info['start_year'],
                'team'       => $a_value_info['team'],
                'level'      => $a_value_info['level'],
                'crew'       => $a_value_info['crew'],
                'creatorid'  => $s_UserID,
                'updaterid'  => $s_UserID,
                'insertdate' => $f_insertdate,
                'updatedate' => $f_insertdate,
            );

            db_insert_row($db_conn, $a_row, 'user_class');
    
        }
        
        if ($a_value_info['father_saint'] || $a_value_info['father_name']) {
        
            $a_row = array (
                    'userid'       => $sNew_ID,
                    'saint'        => $a_value_info['father_saint'],
                    'dearname'     => $a_value_info['father_name'],
                    'address'      => $a_value_info['address'],
                    'phone'        => $a_value_info['phone'],
                    'relationship' => 'CHA',
                    'creatorid'    => $s_UserID,
                    'updaterid'    => $s_UserID,
                    'insertdate'   => $f_insertdate,
                    'updatedate'   => $f_insertdate,
            );
            db_insert_row($db_conn, $a_row, 'user_dear');
        }
        
        if ($a_value_info['mother_saint'] || $a_value_info['mother_name']) {
        
            $a_row = array (
                    'userid'       => $sNew_ID,
                    'saint'        => $a_value_info['mother_saint'],
                    'dearname'     => $a_value_info['mother_name'],
                    'address'      => $a_value_info['address'],
                    'phone'        => $a_value_info['phone'],
                    'relationship' => 'ME',
                    'creatorid'    => $s_UserID,
                    'updaterid'    => $s_UserID,
                    'insertdate'   => $f_insertdate,
                    'updatedate'   => $f_insertdate,
            );
            db_insert_row($db_conn, $a_row, 'user_dear');
        }

        $a_value_info['birthday']          = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['birthday']);
        $a_value_info['baptism_date']      = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['baptism_date']);
        $a_value_info['eucharist_date']    = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['eucharist_date']);
        $a_value_info['confirmation_date'] = preg_replace('/(\d+).(\d+).(\d+)/', '$3-$2-$1', $a_value_info['confirmation_date']);
        
        $a_users[$sNew_ID] = $a_value_info;
    }

    $v_response_json->code = 200;
    $v_response_json->data = array (
        'users'    => $a_users,
        'usertype' => $f_usertype,
        'course'   => $f_course,
    );
    echo json_encode($v_response_json, true);
    exit;
    // </editor-fold>
}
else {
    raise_error('Bạn chưa được cấp quyền thực hiện chức năng này');
}
?>